<?php

use console\db\channels\TransferTableMigration;
use yii\db\Query;
use yii\helpers\StringHelper;

/**
 * 追加泰山号动态
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m300020_000003_t_sns_dynamic_tsline_append extends TransferTableMigration {

    /**
     * @inheritdoc
     */
    public $sourceDb = 'olddb';

    /**
     * @inheritdoc
     */
    public $beforeTruncateTargetTable = false;

    /**
     * @inheritdoc
     */
    public function buildQuery() {
        return (new Query())->from('{{%' . $this->sourceTable . '}}')
        ->where(['type' => 'active'])
        ->orderBy([
            'created_at' => SORT_ASC
        ]);
    }

    /**
     * @inheritdoc
     */
    public function safeDown() {
        $this->delete('{{%' . $this->targetTable . '}}', [
            'group_id' => 2
        ]);
        $this->resetAutoIncrement($this->targetTable);
    }

    /**
     * @inheritdoc
     */
    public function validateTransfer(&$data) {
        if (!parent::validateTransfer($data)) {
            return false;
        }
        if ($data['deleted_at']) {
            return false;
        }
        $message = str_ireplace(['INSERT INTO', 'ALERT', 'script'], '', $data['content']);
        if ($message !== $data['content']) {
            return false;
        }
        $message = trim(strip_tags($message));
        if (!$message) {
            return false;
        }
        $data['content'] = $message;

        return true;
    }

    /**
     * @inheritdoc
     */
    public function getTransferOptions() {
        return [
            'table' => [
                'sns_dynamic' => 'ts_dynamic',
            ],
            'columns' => [
                'topic_id' => 'id',
                'user_id',
                'group_id' => function() {
                    return 2;
                },
                'subject' => function($data) {
                    return StringHelper::truncate($data['content'], 200);
                },
                'status' => function($data) {
                    return $data['status'] >= 0 ? 10 : $data['status'];
                },
                'created_at' => function($data) {
                    return $data['created_at'];
                },
                'updated_at' => function($data) {
                    return $data['updated_at'];
                },
                'deleted_at' => function($data) {
                    return $data['deleted_at'];
                },
            ],
        ];
    }

}
